package com.yc.demohoudun.service;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.demohoudun.VO.UserDetailVO;
import com.yc.demohoudun.entiy.Product;
import com.yc.demohoudun.entiy.Result;
import com.yc.demohoudun.entiy.User;
import com.yc.demohoudun.mapper.UserMapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User login(String username, String password) throws  ServiceException{
        if (username==null || username.isBlank()){
            throw  new ServiceException("请输入用户名！");
        }
        if (password==null || password.isBlank()){
            throw  new ServiceException("请输入密码！");
        }
        User user = userMapper.selectByUsernameAndPassword(username, password);
        if (user==null){
            throw new ServiceException("账号密码错误");
        }

        return user;
    }

    public Result saveUser(User user) {

        String email = user.getEmail();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
          return   new Result(0,"邮箱已被注册",null);
        }

        //默认头像
        user.setHead("https://tse2-mm.cn.bing.net/th/id/OIP-C.-KdypyyEp33RbES_-LRbPAHaHa?rs=1&pid=ImgDetMain");
        userMapper.saveUser(user);
        return   new Result(1,"登陆成功",user);
    }

    public Result fogetPassword(String email) {

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email));

        if (user==null){
            return new Result(0,"此账号未注册",null);
        }
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        user.setCode(code.toString());


return  new Result(1,"登录成功",user);
    }

    public Result selectdatailAndproduct(String username) {

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        UserDetailVO userDetailVO = new UserDetailVO();
        BeanUtils.copyProperties(user,userDetailVO);

        List<Product>  products= userMapper.selectByuser(username);
        userDetailVO.setProducts(products);

        return new Result(1,"个人信息查询成功",userDetailVO);
    }
}
